import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_page_singleton.dart';
import 'package:xindong/manager/xindong_permission_ctr.dart';
import 'package:xindong/models/xindong_file_select_class.dart';
import 'package:xindong/res/assets_res.dart';
import 'package:xindong/routes/user/auth/xindong_auth_ctr.dart';
import 'package:xindong/routes/user/auth/xindong_auth_live_detect_yemian.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/common/xindong_app_bar.dart';
import 'package:xindong/widgets/common/xindong_button.dart';
import 'package:xindong/widgets/dialog/xindong_base_alert.dart';
import 'package:xindong/widgets/dialog/xindong_base_sheet.dart';
import 'package:xindong/widgets/image/xindong_media_add_container.dart';
import 'package:xindong/widgets/image/xindong_media_add_container.dart';

class XinDongAuthFaceTipsYeMian extends StatefulWidget {
  const XinDongAuthFaceTipsYeMian({super.key});

  @override
  State<XinDongAuthFaceTipsYeMian> createState() => _XinDongAuthFaceTipsYeMianState();
}

class _XinDongAuthFaceTipsYeMianState extends State<XinDongAuthFaceTipsYeMian> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XinDongAppBar("真人认证"),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ImageUtil.asset(AssetsRes.IMAGE_FACE_CERTIFICATION, width: 180, height: 180),
            const SizedBox(height: 50),
            const Text(
              "将通过面容识别进行真人认证",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: DZColors.titleColor),
            ),
            const SizedBox(height: 16),
            const Text(
              "面容识别由系统自动完成，只需20秒\n认证成功后即可免费报名女士节目",
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.normal, color: DZColors.contentColor),
            ),
            const SizedBox(height: 26),
            SizedBox(
              width: 268,
              height: kButtonHeight,
              child: XinDongCommonButton("真人认证", onTap: () async {
                // 1、上传一张照片
                XinDongAuthUploadImageDialog.show(onTapStart: (String imageUrl) async {
                  // 2、进行活体检测
                  bool havePermission = await XinDongPermissionCtr.checkPermission(XinDongAppPermission.camera);
                  if (havePermission == false) {
                    showToast("认证需要开启相机权限");
                    return;
                  }
                  XinDongAuthLiveDetectYeMian.show(
                    isLoginStatus: false,
                    doneCallback: (String token) async {
                      // 成功就隐藏弹窗
                      XinDongAuthUploadImageDialog.hide();
                      // 3、提交图片地址和活体检测token给服务端，判断是不是同一个人
                      showLoading();
                      await XinDongAuthCtr.to.requestAuthFace(token: token, imageUrl: imageUrl);
                      hideLoading();
                    },
                  );
                });
              }),
            ),
          ],
        ),
      ),
    );
  }
}

class XinDongAuthUploadImageDialog extends StatefulWidget {
  final Function(String avatarUrl) onTapStart;

  XinDongAuthUploadImageDialog.show({super.key, required this.onTapStart}) {
    showAlertDialog(alert: this);
  }

  static hide() {
    Navigator.pop(currentContext());
  }

  @override
  State<XinDongAuthUploadImageDialog> createState() => _XinDongAuthUploadImageDialogState();
}

class _XinDongAuthUploadImageDialogState extends State<XinDongAuthUploadImageDialog> {
  String imageUrl = "";
  File? imageFile;

  _onTapUpload() async {
    if (imageFile == null) {
      showToast("请先上传照片");
      return;
    }
    if (TextUtil.isEmpty(imageUrl)) {
      showLoading();
      final fileUrl = await XinDongNetworking.instance.uploadFile(filePath: imageFile!.path);
      if (!TextUtil.isEmpty(fileUrl)) {
        mDebugPrint('返回图片结果$fileUrl');
        // 记录头像地址
        imageUrl = fileUrl!;
      }
      hideLoading();
    }
    widget.onTapStart(imageUrl);
  }

  @override
  void dispose() {
    XinDongMediaAddContainer.delete();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return XinDongBaseDialog(
      body: Container(
        width: 300,
        padding: const EdgeInsets.all(24),
        decoration: BoxDecoration(color: DZColors.dialog, borderRadius: BorderRadius.circular(16)),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 100,
              height: 100,
              child: XinDongMediaAddContainer(
                maxCount: 1,
                columns: 1,
                supportType: MediaSupportType.onlyImage,
                onSelect: (images, video) {
                  if (images != null && images.isNotEmpty) {
                    imageFile = images.first.file;
                  } else {
                    imageFile = null;
                  }
                },
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              "上传1张形象良好的正脸照片\n保证照片像素清晰、五官可见\n请在光线充足的位置进行认证\n通过认证后，此照片将上传到你的相册",
              style: TextStyle(fontSize: 14, color: DZColors.titleColor, height: 1.8),
            ),
            const SizedBox(height: 16),
            SizedBox(
              height: 40,
              child: XinDongCommonButton("面容识别", onTap: _onTapUpload),
            ),
          ],
        ),
      ),
    );
  }
}
